<template>
    <div class="image-preview" v-if="show" @click="hidePreview">
        <image class="photo" :src="src" @load="resizeImage" ref="photo" @longpress="saveImage" resize="contain"></image>
        <wxc-dialog title="保存图片" :show="DialogShow"
                    @wxcDialogCancelBtnClicked="wxcDialogCancelBtnClicked" @wxcDialogConfirmBtnClicked="wxcDialogConfirmBtnClicked">
        </wxc-dialog>
    </div>
</template>

<script>
import { WxcDialog } from 'weex-ui'
const modal = weex.requireModule('modal')
const animation = weex.requireModule('animation')

export default {
  name: 'preview',
  props: ['show', 'src'],
  components: {WxcDialog},
  data () {
    return {
      DialogShow: false // 弹窗显示
    }
  },
  methods: {
    wxcDialogCancelBtnClicked () {
      this.DialogShow = false
    },
    loadImage (e) {
      const that = this
      const view = that.$refs.photo
      if (event.success) {
        let k = event.size.naturalWidth / event.size.naturalHeight
        animation.transition(view, {
          styles: {
            width: 750 + 'px',
            height: parseInt(750 / k) + 'px'
          },
          duration: 0,
          timingFunction: 'ease',
          delay: 0,
          needLayout: true
        }, function () {})
      }
    },
    wxcDialogConfirmBtnClicked () {
      const $image = this.$refs.photo
      $image.save(result => {
        if (result.success) {
          modal.toast({
            message: '保存成功'
          })
        } else {
          modal.toast({
            message: '保存失败'
          })
        }
        this.DialogShow = false
      })
    },
    saveImage (e) {
      this.DialogShow = true
    },
    hidePreview () {
      this.$emit('hidePreview')
    }
  }
}
</script>

<style scoped>
    .image-preview {
        position: fixed;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        background-color: #000;
    }
    .photo {
        width: 750px;
        height: 800px;
    }
</style>
